<template>
    <div class="app-container">


        <div class="search-container" ref="search">
            <el-form ref="queryFormRef" :model="queryParams" :inline="true" size="default">
                <el-form-item label="是否绑定" prop="status">
                    <el-select v-model="queryParams.status" placeholder="选择素材分类" clearable style="width: 200px"
                        @change="handleQuery">
                        <el-option label="待绑定" value="1" />
                        <el-option label="已绑定" value="2" />
                    </el-select>
                </el-form-item>
                <el-form-item label="开始时间" prop="sta_time">
                    <el-date-picker class="w-200" v-model="queryParams.sta_time" type="datetime" placeholder="选择日期"
                        value-format="YYYY-MM-DD hh:mm:ss"></el-date-picker>
                </el-form-item>
                <el-form-item label="结束时间" prop="end_time">
                    <el-date-picker class="w-200" v-model="queryParams.end_time" type="datetime" placeholder="选择日期"
                        value-format="YYYY-MM-DD hh:mm:ss"></el-date-picker>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="getLists">搜索</el-button>
                    <el-button @click="resetQuery">重置</el-button>
                </el-form-item>
            </el-form>
        </div>

        <el-card shadow="never">
            <template #header>
                <el-button size="default" @click="goBack" type="primary">返回</el-button>
                <el-button size="default" type="primary" @click="hanldeDelete">批量删除</el-button>
                <el-button size="default" type="primary" @click="addQrCode">生成二维码</el-button>
            </template>
            <el-table :height="pageHeight + 'px'" :data="tableData" @selection-change="handleSelectionChange">
                <el-table-column type="selection" width="55"></el-table-column>
                <el-table-column label="企业单位" align="center" prop="bang_site"> </el-table-column>
                <el-table-column label="是否绑定" align="center" prop="status" :formatter="qrCodeStatus"></el-table-column>
                <el-table-column label="创建时间" align="center" prop="update_time"></el-table-column>
                <el-table-column label="url" prop="url" align="center">
                    <template #default="scope">
                        <el-button style="color: #409eff" type="text"
                            @click="handleCopyLink(scope.row)">复制URL</el-button>
                    </template>
                </el-table-column>
                <el-table-column label="二维码" prop="qr_src" align="center">
                    <template #default="scope">
                        <div class="qr-wrapper" @click="showQrCodeDetail(scope.row)">
                            <img :src="upDataUrl + scope.row.src" class="qr-img" />
                            <span class="qr-tip">点击查看</span>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
            <div class="block">
                <el-pagination @current-change="handleCurrentChange" v-model:currentPage="tableDataInfo.page"
                    :page-count="tableDataInfo.total_page" :total="tableDataInfo.total"
                    layout="total,prev, pager, next, jumper" background>
                    <!-- :hide-on-single-page="true" -->
                </el-pagination>
            </div>
        </el-card>



        <el-dialog v-model="dialogFormVisible" width="30%" @close="closeDialog" :close-on-click-modal="false">
            <el-form ref="childForm" :rules="rules" :model="formData" label-position="top">
                <el-row>
                    <el-col :span="6" :offset="6">
                        <el-form-item label="二维码张数" prop="number">
                            <!-- <el-input v-model="formData.number"></el-input> -->
                            <el-input-number v-model="formData.number" :min="1" label="描述文字"></el-input-number>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button size="default" @click="dialogFormVisible = false">取 消</el-button>
                    <el-button size="default" type="primary" @click="submitForm">确 定</el-button>
                </span>
            </template>
        </el-dialog>
        <el-dialog v-model="qrModalVisible" width="18%" center="true" :close-on-click-modal="false">
            <div class="qr-modal-wrapper" ref="qrImg">
                <img :src="qrModalData.qrSrc" class="qr-modal-img" />
                <span>{{ qrModalData.qrCode }}</span>
            </div>
            <div class="qr-modal-download">
                <el-button type="primary" @click="downloadQrImg">点击下载</el-button>
            </div>
        </el-dialog>
    </div>
</template>
<script>
import storage from '@/util/storage'
import html2canvas from 'html2canvas'
import { ElMessage } from 'element-plus'
export default {
    data() {
        return {
            tableData: [],
            tableDataInfo: '',
            fatherId: '',
            dialogFormVisible: false,
            formData: {
                number: 10,
                unit_id: ''
            },
            rules: {
                number: [{ required: true, message: '请输入', trigger: 'blur' }],
                unit_id: [{ required: true, message: '请选择', trigger: 'blur' }]
            },
            id: '',
            qrModalVisible: false,
            qrModalData: {},
            upDataUrl: import.meta.env.DEV ? '/proxy/' : import.meta.env.VITE_APP_API_BASEURL,
            pageHeight: 0,
            queryParams: {},
            page: 1,
            pageSize: 10,
            ids: []
        }
    },
    computed: {
        upLoadImgHeader() {
            return {
                'A-Token': this.$store.state.user.a_token,
                'U-Token': this.$store.state.user.u_token
            }
        }
    },
    mounted() {
        this.pageHeight = window.innerHeight - this.$refs.search.clientHeight - 260;
    },
    created() {
        this.fatherId = this.$route.query.id
        if (this.$route.query.from) this.from = this.$route.query.from
        console.log(this.$route.query.from)
        if (this.$route.query.unitIdFromChild) this.unitIdFromChild = this.$route.query.unitIdFromChild
        this.formData.unit_id = this.$route.query.id
        this.getLists()
    },

    methods: {
        hanldeDelete() {
            if (this.ids.length == 0) {
                this.$message({
                    message: '请选择要删除的数据',
                    type: 'warning'
                });
                return
            }
            this.$confirm('你确定删除这些数据吗', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.post('/unit/QrCode/batchDeletion', {
                    ids: this.ids
                }).then(res => {
                    if (res.code == 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });
                        this.getLists()
                    }
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                })
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });
            });
        },
        handleSelectionChange(row) {
            this.ids = row.map(item => item.id)
        },
        // 重置form
        resetQuery() {
            this.page = 1;
            this.$refs['queryFormRef'].resetFields();
            this.getLists()
        },
        goBack() {
            this.$router.go(-1)
        },
        downloadQrImg() {
            let that = this
            html2canvas(that.$refs.qrImg, {
                useCORS: true
            }).then((canvas) => {
                let _url = canvas.toDataURL('image/png')
                let a = document.createElement('a')
                a.href = _url
                a.download = '二维码'
                a.click()
            })
        },
        showQrCodeDetail(data) {
            let that = this
            this.qrModalVisible = true
            this.$api
                .post('/index/Qrcode/getBase64', {
                    src: data.src
                })
                .then((res) => {
                    that.qrModalData = {
                        qrSrc: res.data,
                        qrCode: data.qr_code_no,
                        name: data.name
                    }
                    if (this.from !== 'unit_child') {
                        //子单位
                        this.qrModalData.unitName = data.unit_name
                    } else {
                        this.qrModalData.unitName = data.sub_unit_name
                    }
                })
        },
        qrCodeStatus(row, column, cellValue, index) {
            let temp = ['', '待绑定', '已绑定']
            return temp[cellValue]
        },
        getLists() {

            let user_info = this.$store.state.user.user_info
            let query = {
                region_id: user_info.region_id,
                page: this.page,
                rows: this.pageSize,
                ...this.queryParams
            }
            query.sub_unit_id = this.$route.query.id
            this.$api.post('/unit/QrCode/lists', query).then((res) => {
                this.tableData = res.data.lists
                this.tableDataInfo = res.data
            })
        },
        addQrCode() {
            this.dialogFormVisible = true
        },
        closeDialog() {
            this.$refs.childForm.resetFields()
            let temp = this.formData
            for (let key in temp) {
                temp[key] = ''
            }
            this.formData = temp
        },
        handleSizeChange(e) {
            this.pageSize = e;
            this.getDataList()
        },
        handleCurrentChange(e) {
            this.page = e;
            this.getLists()
        },
        handleCopyLink(row) {
            console.log(row.url)
            let _this = this
            console.log(this)
            _this.$copyText(row.url).then(
                function (e) {
                    _this.$message({
                        showClose: true,
                        message: '复制成功',
                        type: 'success'
                    })
                },
                function (e) {
                    _this.$message({
                        showClose: true,
                        message: '复制失败，请手动复制',
                        type: 'error'
                    })
                }
            )
        },
        submitForm() {
            this.$refs.childForm.validate((valid) => {
                if (valid) {
                    let data = this.formData
                    data.sub_unit_id = this.fatherId
                    this.$api.post('/unit/QrCode/create', data).then(() => {
                        this.getLists()
                        this.dialogFormVisible = false
                    })
                } else {
                    ElMessage.error('请填写完整')
                    return false
                }
            })
        }
    }
}
</script>
<style scoped>
.block {
    display: flex;
    justify-content: center;
}

.qr-wrapper {
    display: flex;
    justify-content: space-between;
    flex-direction: column;
    align-items: center;
    cursor: pointer;
}

.qr-img {
    width: 50px;
    height: 50px;
}

.qr-tip {
    text-align: center;
}

.qr-tip:hover {
    color: #5482ee;
    text-decoration: underline;
}

.qr-modal-wrapper {
    display: flex;
    justify-content: space-around;
    flex-direction: column;
    padding: 30px 0;
}

.qr-modal-wrapper span {
    display: flex;
    justify-content: space-around;
    align-items: center;
    line-height: 24px;
}

.qr-modal-img {
    width: 200px;
    height: 200px;
    margin: 0 auto;
}

.qr-modal-download {
    display: flex;
    justify-content: space-around;
    align-items: center;
    margin-top: 30px;
}
</style>
